package com.heima.admin.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminMapper;
import com.heima.admin.service.AdminService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdminUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class AdminServiceimp extends ServiceImpl<AdminMapper,AdminUser> implements AdminService {
    /**
     * 登录模块
     * @param dto
     * @return
     */

    @Override
    public ResponseResult log(AdUserDto dto) {
        if (StringUtils.isNotBlank(dto.getName())&&StringUtils.isNotBlank(dto.getPassword())){
            LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AdminUser::getName,dto.getName());
            AdminUser one = getOne(queryWrapper);
            if (one==null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "账号不存在");
            }
            //获取前端传过来的密码
            String password = dto.getPassword();
            //数据库的盐
            String salt = one.getSalt();
            //通过工具类生成密码
//          String mdpassword = MD5Utils.encodeWithSalt(password,salt);
            String md5DigestAsHex = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (!one.getPassword().equals(md5DigestAsHex)){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //生成token
            String token = AppJwtUtil.getToken(one.getId().longValue());
            one.setPassword("");
            one.setSalt("");
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("user",one);
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
    }
}
